//
//  JZHAddAdderssViewController.m
//  极致荟
//
//  Created by hetao on 14-8-22.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHAddAdderssViewController.h"
#import "JZHAdders.h"
@interface JZHAddAdderssViewController ()
{
    NSArray *sheng;
    NSArray *shi;
    NSArray *qu;
    JZHAdders *addersMode;
}
@property (weak, nonatomic) IBOutlet UIPickerView *picke;
@property (weak, nonatomic) IBOutlet UIScrollView *scorll;
@property (strong, nonatomic) IBOutlet UIView *pickview;

@end

@implementation JZHAddAdderssViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initAdders:(JZHAdders *)adders
{
    self=[[JZHAddAdderssViewController alloc] init];
    addersMode=adders;
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    sheng=[[NSArray alloc] init];
    shi=[[NSArray alloc] init];
    qu=[[NSArray alloc] init];
    if(addersMode)
    {
        self.addname.text=addersMode.name;
        self.addphone.text=addersMode.phone;
        self.youz.text=addersMode.postCode;
        self.content.text=addersMode.content;
        self.address.text=addersMode.addres;
    }
    [self dicfileplist];
    self.navigationItem.title=@"地址填写";
    [self.address setInputView:self.pickview];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    UIButton *rehie=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
    [rehie setTitle:@"保存" forState:UIControlStateNormal];
    
    [rehie setTitleColor:[UIColor colorWithRed:0/255.0 green:139/255.0 blue:255/255.0 alpha:1] forState:UIControlStateNormal];
    [rehie addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [rehie setTintColor:[UIColor blueColor]];
     UIBarButtonItem *rBarButton = [[UIBarButtonItem alloc] initWithCustomView:rehie];
    self.navigationItem.rightBarButtonItem=rBarButton;
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self.scorll setContentSize:CGSizeMake(0, self.scorll.frame.size.height+1)];
    [self.addphone setKeyboardType:UIKeyboardTypeNumberPad];
    [self.youz setKeyboardType:UIKeyboardTypeNumberPad];
    [self.scorll addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyend:)]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(not:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyend:(UITapGestureRecognizer *)tap
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
   [self.scorll setContentOffset:CGPointMake(0, 0) animated:YES];

}

- (void)not:(NSNotification *)no
{
    if([self.content isFirstResponder] || [self.youz isFirstResponder ]  )
    {
        if(self.scorll.contentOffset.y==0)
        {
            [self.scorll setContentOffset:CGPointMake(0, 50) animated:YES];
        }
      
       
    }
}
- (void)leftDrawerButtonPress:(UIButton *)but
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)textViewDidChangeSelection:(UITextView *)textView
{
    if(textView.text.length==0)
    {
        self.tstext.hidden=NO;
    }else
    {
        self.tstext.hidden=YES;
    }
}
- (void)save:(UIButton *)sender
{
    [self addaddersHttp];
}
///在没有本地缓存的情况下取值
- (void)httpAddData:(NSString *)path
{
    [HttpRequest httpRequestPost:JZHHTTPURL(@"myInformation/getRegionData") parameters:nil block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            NSLog(@"%@",data);
            sheng=[[data objectForKey:@"data"] objectForKey:@"list"];
            [self shi:sheng[0]];
            [self.picke reloadAllComponents];
            
            [sheng writeToFile:path atomically:YES];
            
        }
    }];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
       return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component==0)
    {
        return sheng.count;
    }
    
    if(component==1)
    {
        return shi.count;
    }else
    {
        return qu.count;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
       return 30;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *lab=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 105, 30)];
    lab.textAlignment=NSTextAlignmentCenter;
    lab.font=[UIFont systemFontOfSize:14.0];
    if(component==0)
    {
        lab.text=[sheng [row] objectForKey:@"name"];
    }
    if(component==1)
    {
        lab.text=[shi[row] objectForKey:@"name"];
    }
    if(component==2)
    {
        lab.text=[qu[row] objectForKey:@"name"];
    }
    return lab;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(component==0)
    {
        [self shi:sheng[row]];
        [self.picke reloadAllComponents];
      
    }
    if(component==1)
    {
        [self qu:shi[row]];
        [self.picke reloadAllComponents];
    }
    
    if(component==2 && qu)
    {
        [self pistcodetext:qu[row]];
    }
}
- (void)shi:(id )dic
{
    shi=[dic objectForKey:@"cityList"];
    [self.picke selectRow:0 inComponent:1 animated:NO];
    [self qu:shi[0]];
}

- (void)qu:(id)dic
{
     [self.picke selectRow:0 inComponent:2 animated:NO];
    qu=[dic objectForKey:@"districtList"];
    if([dic objectForKey:@"districtList"]!=[NSNull null])
    {
        [self pistcodetext:qu[0]];
    }
   
}
- (void)pistcodetext:(id)dic
{
    self.youz.text=[dic objectForKey:@"postCode"];
}

- (void)addaddersHttp
{
    if([self.addname.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length<2)
    {
        return;
    }
    
    if(self.addphone.text.length!=11)
    {
        return;
    }
    
    if(self.content.text.length<4)
    {
        return;
    }
    
    if(self.address.text.length<3)
    {
        return;
    }
    
    if(self.youz.text.length<2)
    {
        return;
    }
    
    NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:self.addname.text,@"Consignee",self.addphone.text,@"Telphone",self.address.text,@"simpleAddress",self.content.text,@"detailAddress",self.youz.text,@"postCode",[NSNumber numberWithInt:[User defuceUser].userId],@"userId", nil];
    
    [HttpRequest httpRequestPost:JZHHTTPURL(@"myInformation/adddetailAddress") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            JZHAdders *adders=[[JZHAdders alloc] init];
            adders.addres=self.address.text;
            adders.addid=[[data objectForKey:@"data"] objectForKey:@"addressId"];
            adders.content=self.content.text;
            adders.name=self.addname.text;
            adders.phone=self.addphone.text;
            adders.postCode=self.youz.text;
            if([User defuceUser].address)
            {
                [[User defuceUser].address addObject:adders];
            }else
            {
                [User defuceUser].address=[[NSMutableArray alloc] initWithObjects:adders, nil];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
- (void)dicfileplist
{
    NSString *path=NSHomeDirectory();
    path=[path stringByAppendingString:@"/Documents/AddersList.plist"];
    NSArray *arr=[[NSArray alloc] initWithContentsOfFile:path];
    if(!arr)
    {
        NSLog(@"没有缓存");
        [self httpAddData:path];
        
    }else
    {
        sheng=arr;
        [self shi:sheng[0]];
        [self.picke reloadAllComponents];
    }
}
- (IBAction)ok:(id)sender
{
    
    
    UILabel *lab=(UILabel *)[self.picke viewForRow:[self.picke selectedRowInComponent:0] forComponent:0];
    NSString *str=[lab.text stringByAppendingString:@" "];
    lab =(UILabel *)[self.picke viewForRow:[self.picke selectedRowInComponent:1] forComponent:1];
    str=[[str stringByAppendingString:lab.text] stringByAppendingString:@" "];
    lab =(UILabel *)[self.picke viewForRow:[self.picke selectedRowInComponent:2] forComponent:2];
    str=[str stringByAppendingString:lab.text];
    self.address.text= str;
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}
- (IBAction)close:(id)sender
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}
@end
